﻿

using DataService.IService;
using DataService.Core.Extensions;
using System.Collections.Generic;
using DataService.Core.ServiceDTO;
using DataService.DataAccessLayer;
using System.Data.Common;
using DataService.Remote.DataAccessLayer.Provider;

namespace DataService
{
    public static class DBMangerFactory
    {
        private static readonly Dictionary<DatabaseType, IDatabaseProvider> _providerDic = new Dictionary<DatabaseType, IDatabaseProvider>();
        private static readonly Dictionary<DatabaseType, IRemoteDB> _dbs = new Dictionary<DatabaseType, IRemoteDB>();
        static DBMangerFactory()
        {
            RegisterProvider<SqlServerProvider>(DatabaseType.SqlServer);
            RegisterProvider<SQLiteProvider>(DatabaseType.SQLite);
            RegisterProvider<MySqlProvider>(DatabaseType.MySql);
            RegisterProvider<OracleProvider>(DatabaseType.Oracle);
            RegisterProvider<DMProvider>(DatabaseType.DaMeng);
            Register<SqlServer>(DatabaseType.SqlServer);
            Register<SQLite>(DatabaseType.SQLite);
            Register<Oracle>(DatabaseType.Oracle);
            Register<DataService.DataAccessLayer.MySql>(DatabaseType.MySql);
            Register<DataService.DataAccessLayer.DM>(DatabaseType.DaMeng);
        }
        /// <summary>注册数据库提供者</summary>
        private static void RegisterProvider<T>(DatabaseType dbType) where T : IDatabaseProvider, new() => _providerDic[dbType] = new T();
        /// <summary>注册数据库连接工厂</summary>
        private static void Register<T>(DatabaseType dbType) where T : IRemoteDB, new() => _dbs[dbType] = new T();
        /// <summary>根据数据库类型创建提供者</summary>
        /// <param name="dbType"></param>
        /// <returns></returns>
        public static IRemoteDB Create(DatabaseType dbType)
        {

            var db = _dbs[dbType]?.GetType().CreateInstance() as IRemoteDB;
            return db;
        }
        /// <summary>创建数据库工厂</summary>
        /// <param name="dbType"></param>
        /// <returns></returns>
        public static IDatabaseProvider CreateProvider(DatabaseType dbType)
        {
            var dbProvider = _providerDic[dbType]?.GetType().CreateInstance() as IDatabaseProvider;
            return dbProvider;
        }
    }
}
